<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/7
 * Time: 13:51
 */

namespace App\Process;


use App\Enums\UrlEnums;
use App\Library\Auth;
use App\Task\TeamInfoTask;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Component\Timer;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use EasySwoole\HttpClient\HttpClient;
use EasySwoole\MysqliPool\Mysql;

class Team extends AbstractProcess
{
    public function run($arg)
    {
        go(function ()use($arg){
            Timer::getInstance()->loop(1000*60*60*24*30,function (){
                //战队列表
                $teamListsUrl = UrlEnums::FJURL.UrlEnums::TEAM_LISTS_PATH.'?offset=0&limit=999&version=2';
                $teamLists = new HttpClient($teamListsUrl);
                list($s1, $s2) = explode(' ', microtime());
                $microtime = (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000); //毫秒时间戳
                $option = [
                    'path' => UrlEnums::TEAM_LISTS_PATH,
                    'api_time'  => $microtime
                ];
                $header = Auth::getInstance($option)->header();
                $teamLists->setHeaders($header,true,false);
                $response = $teamLists->get();
                $data = $response->getBody();
                $data = json_decode($data,true);
                $db = Mysql::defer('mysql');
                $team_ids = $db->getColumn('siam_team','team_id');
                if( $data['code'] != 200 || empty($data['data']) ){
                    return false;
                }
                foreach ( $data['data'] as $k=>$v ){
                    $data['data'][$k]['game'] = 'lol';
                }
                if( empty($team_ids) ){
                    $db->insertMulti('siam_team',$data['data']);
                }
                foreach ( $data['data'] as $item ){
                    if( in_array($item['team_id'],$team_ids) ){
                        $db->where('team_id',$item['team_id'])->where('game','lol')->update('siam_team',[
                            'name'      => $item['name'],
                            'logo'      => $item['logo'],
                            'name_en'   => $item['name_en'],
                            'short_name'=> $item['short_name'],
                            'introduction' => $item['introduction']
                        ]);
                    }else{
                        $db->insert('siam_team',$item);
                    }
                    //战队基本信息--start--
                    TaskManager::async(new TeamInfoTask(['team_id'=>$item['team_id']]));
                    //战队基本信息--end--
                }

                //战队基本信息

            });
        });
    }
}